#
#	genx_store.py
#
#	David Janes
#	2008.08.16
#
#	GenX - search, create and insert structured data
#

import sys
import types
import re
import pprint
import cgi
import md5
import imp
import os
import os.path
import traceback

import genx_helpers
import genx_cfg
import bm_text

try:
	import json
except:
	import simplejson as json

class StoreMixin:
	def __init__(self):
		pass

	def MakeIID(self, local_id):
		return	md5.new(bm_text.toutf8(local_id)).hexdigest()

	def Load(self, iid, ctype, subid = None):
		path = self.StorePath(iid = iid, ctype = ctype, subid = subid)
		fullpath = os.path.join(genx_cfg.cfg["home_path"], path)

		try:
			try:
				if not os.path.isfile(fullpath):
					return	None

				fout = open(fullpath, 'rb')
				return	fout.read()
			finally:
				try: fout.close()
				except: pass
		except IOError:
			traceback.print_exc(file = sys.stderr)
			return	None

	def LoadAsJson(self, iid, subid = None):
		data = self.Load(iid = iid, ctype = "application/json", subid = subid)
		if data:
			try:
				return	json.loads(data)
			except:
				pass

		return	None
		
	def StoreAsJson(self, iid, object, subid = None):
		self.Store(iid = iid, data = json.dumps(object), ctype = "application/json", subid = subid)

	def Store(self, iid, data, ctype, subid = None):
		path = self.StorePath(iid = iid, ctype = ctype, subid = subid)
		fullpath = os.path.join(genx_cfg.cfg["home_path"], path)

		try:
			dir = os.path.dirname(fullpath)
			if not os.path.isdir(dir):
				os.makedirs(dir)
				os.chmod(dir, genx_cfg.cfg["chmod_dir"])
		except:
			traceback.print_exc(file = sys.stderr)
			pass

		try:
			try:
				fout = open(fullpath, 'wb')
				fout.write(data)

				os.chmod(fullpath, genx_cfg.cfg["chmod_file"])
			finally:
				try: fout.close()
				except: pass
		except IOError:
			traceback.print_exc(file = sys.stderr)
			return	None

		return	{
			"uri" : "%s/%s" % ( genx_cfg.cfg["home_uri"].rstrip("/"), path, ),
			"path" : path,
		}

	def StorePath(self, iid, ctype, subid = None):
		if ctype in [ "image/jpeg", ]: extension = "jpg"
		elif ctype in [ "image/gif", ]: extension = "gif"
		elif ctype in [ "image/png", ]: extension = "png"
		elif ctype in [ "application/json", ]: extension = "json"
		else:
			extension = "dat"

		if subid:
			path = "%s/%s/%s.%s.%s" % (
				"images",
				self.p_qid,
				iid,
				subid,
				extension,
			)
		else:
			path = "%s/%s/%s.%s" % (
				"images",
				self.p_qid,
				iid,
				extension,
			)

		return	path
